<template>
	<view class="post-creation-container">
		<!-- 顶部导航栏 -->
		<view class="top-navbar">
			<view class="container-fluid">
				<view class="row align-items-center">
					<view class="col-lg-3 col-md-3 col-sm-12">
						<view class="logo">
							<image src="/static/petLogo.png" mode="aspectFit"></image>
							<text class="titleText">宠物健康管家</text>
						</view>
					</view>
					<view class="col-lg-6 col-md-6 col-sm-12">
						<view class="navbar-center">
							<!-- 分类导航移到这里 -->
							<view class="nav-categories">
								<view class="nav-item" @click="goIndex">
									<text class="titleText">首页</text>
								</view>
								<view class="nav-item" @click="goHealth">
									<text class="titleText">健康</text>
								</view>
								<view class="nav-item" @click="goShop">
									<text class="titleText">商城</text>
								</view>
								<view class="nav-item" @click="goForum">
									<text class="titleText">论坛</text>
								</view>
							</view>
							<!-- 搜索栏缩短 -->
							<view class="search-container">
								<image src="/static/index/search-icon.png" mode="aspectFill"></image>
								<input type="text" placeholder="搜索宠物食品" class="search-input" />
								<button class="search-btn">搜索</button>
							</view>
						</view>
					</view>
					<view class="col-lg-3">
						<view class="user-actions">
							<view class="action-item" @click="goMine">
								<image src="/static/Tabbar/mine.png" style="width: 60rpx;height: 60rpx;"
									mode="aspectFill"></image>
								<text class="titleText">我的账户</text>
							</view>
							<view class="action-item" @click="goShopCar">
								<image src="/static/Tabbar/shop.png" style="width: 60rpx;height: 60rpx;"
									mode="aspectFill"></image>
								<text class="titleText">购物车</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 发布表单 -->
		<view class="post-form">
			<!-- 用户信息展示 -->
			<view class="user-info">
				<image :src="userInfo.avatar" class="user-avatar"></image>
				<text class="username">{{ userInfo.username }}</text>
			</view>

			<!-- 内容输入区 -->
			<view class="content-area">
				<textarea class="content-input" v-model="postContent" placeholder="分享您的宠物故事..." maxlength="500"
					auto-height></textarea>
				<text class="word-count">{{ postContent.length }}/500</text>
			</view>

			<!-- 图片上传区 -->
			<view class="image-upload-area">
				<view class="upload-title">
					<text class="section-subtitle">添加图片</text>
					<text class="upload-count">{{ imageList.length }}/9</text>
				</view>

				<view class="image-grid">
					<view v-for="(image, index) in imageList" :key="index" class="image-item">
						<image :src="image" class="preview-image" mode="aspectFill"></image>
						<text class="delete-btn" @click="removeImage(index)">×</text>
					</view>

					<view class="image-item add-image" @click="chooseImage" v-if="imageList.length < 9">
						<text class="add-icon">+</text>
					</view>
				</view>
			</view>

			<!-- 话题选择区 -->
			<view class="topic-selection">
				<view class="section-subtitle">添加话题</view>
				<scroll-view scroll-x="true" class="topic-scroll" show-scrollbar="false">
					<view v-for="(topic, index) in topicList" :key="index" class="topic-item"
						:class="{ 'topic-selected': selectedTopics.includes(topic.id) }" @click="toggleTopic(topic.id)">
						<text class="topic-text">#{{ topic.name }}</text>
					</view>
				</scroll-view>
			</view>

			<!-- 位置信息 -->
			<!-- <view class="location-area" @click="chooseLocation">
				<text class="location-icon">📍</text>
				<text class="location-text">{{ location ? location : '添加位置' }}</text>
				<text class="arrow-right" v-if="!location">></text>
				<text class="clear-location" v-if="location" @click.stop="clearLocation">×</text>
			</view> -->

			<!-- 权限设置 -->
			<view class="privacy-setting">
				<text class="privacy-label">谁可以看到</text>
				<picker @change="onPrivacyChange" :value="privacyIndex" :range="privacyOptions">
					<view class="picker-value">
						<text>{{ privacyOptions[privacyIndex] }}</text>
						<text class="arrow-right">></text>
					</view>
				</picker>
			</view>
		</view>

		<!-- 发布按钮 -->
		<view class="submit-area">
			<button class="submit-btn" :disabled="!isFormValid" :class="{ 'btn-disabled': !isFormValid }"
				@click="submitPost">发布</button>
		</view>
	</view>
</template>

<script>
	import titleBar from '@/components/titleBar.vue'
	import {
		dynamics,
		userApi
	} from '@/api/user.js'

	export default {
		components: {
			titleBar
		},
		data() {
			return {
				userInfo: {
					username: '',
					avatar: ''
				},
				postContent: '',
				imageList: [],
				location: '',
				privacyOptions: ['所有人可见', '仅关注者可见', '仅自己可见'],
				privacyIndex: 0,
				topicList: [{
						id: 1,
						name: '萌宠日常'
					},
					{
						id: 2,
						name: '宠物饮食'
					},
					{
						id: 3,
						name: '宠物健康'
					},
					{
						id: 4,
						name: '猫咪'
					},
					{
						id: 5,
						name: '狗狗'
					},
					{
						id: 6,
						name: '宠物用品推荐'
					},
					{
						id: 7,
						name: '宠物训练'
					},
					{
						id: 8,
						name: '宠物医疗'
					}
				],
				selectedTopics: []
			}
		},
		computed: {
			isFormValid() {
				// 至少需要填写内容或上传图片之一
				return this.postContent.trim().length > 0 || this.imageList.length > 0;
			}
		},
		mounted() {
			this.getUserInfo()
		},
		methods: {
			async getUserInfo() {
				try {
					const result = await userApi.getUserInfo()
					this.userInfo = result
					console.log('获取用户信息成功：', this.userAvatar);
				} catch (error) {
					uni.showToast({
						title: '获取用户信息失败: ' + (error.message || '未知错误'),
						icon: 'none'
					});
					console.error('获取用户信息失败：', error);
				}
			},
			// 选择图片
			async chooseImage() {
				try {
					const {
						tempFilePaths
					} = await uni.chooseImage({
						count: 9 - this.imageList.length, // 最多可选数量
						sizeType: ['compressed'], // 压缩图片，减少上传数据量
						sourceType: ['album', 'camera'] // 支持从相册选择或使用相机拍照
					});

					// 判断是否选择了图片
					if (tempFilePaths && tempFilePaths.length > 0) {
						// 显示上传中提示
						uni.showLoading({
							title: '上传中...'
						});
						const result = await userApi.uploadAvatar(tempFilePaths[0]);
						// 依次上传每张图片
						// const uploadPromises = tempFilePaths.map(path => {
						// 	return new Promise(async (resolve, reject) => {
						// 		try {
						// 			// 这里应该使用适合上传动态图片的API，而不是uploadAvatar
						// 			const result = await userApi.uploadAvatar(
						// 			path); // 假设有一个uploadImage方法
						// 			resolve(result.imageUrl || result.url); // 根据实际返回结果调整
						// 		} catch (error) {
						// 			reject(error);
						// 		}
						// 	});
						// });

						// 等待所有图片上传完成
						// const uploadedImages = await Promise.all(uploadPromises);

						// 隐藏加载中
						uni.hideLoading();

						// 将上传成功的图片添加到列表
						this.imageList = [...this.imageList, ...result];

						uni.showToast({
							title: '上传成功',
							icon: 'success'
						});
					}
				} catch (error) {
					uni.hideLoading();
					console.error('选择或上传图片失败:', error);
					uni.showToast({
						title: '上传失败，请重试',
						icon: 'none'
					});
				}
			},
			// chooseImage() {
			// 	uni.chooseImage({
			// 		count: 9 - this.imageList.length,
			// 		sizeType: ['compressed'],
			// 		sourceType: ['album', 'camera'],
			// 		success: (res) => {
			// 			this.imageList = [...this.imageList, ...res.tempFilePaths];
			// 		}
			// 	});
			// },

			// 移除图片
			removeImage(index) {
				this.imageList.splice(index, 1);
			},

			// 切换话题选择
			toggleTopic(topicId) {
				const index = this.selectedTopics.indexOf(topicId);
				if (index === -1) {
					this.selectedTopics.push(topicId);
				} else {
					this.selectedTopics.splice(index, 1);
				}
			},

			// 选择位置
			chooseLocation() {
				uni.chooseLocation({
					success: (res) => {
						this.location = res.name;
					}
				});
			},

			// 清除位置
			clearLocation() {
				this.location = '';
			},

			// 隐私设置变更
			onPrivacyChange(e) {
				this.privacyIndex = e.detail.value;
			},

			// 提交发布
			async submitPost() {
				try {
					if (!this.isFormValid) {
						return;
					}

					// 显示加载中
					uni.showLoading({
						title: '发布中...'
					});

					// 构建发布数据
					const postData = {
						content: this.postContent,
						picture: this.imageList,
						label: 1,
						location: '浙江',
					};

					const result = await dynamics.putPost(postData)
					console.log(this.imageList);
					// 这里应该调用API上传数据
					// 模拟上传过程
					setTimeout(() => {
						uni.hideLoading();
						uni.showToast({
							title: '发布成功',
							icon: 'success'
						});

						// 清空表单
						this.postContent = '';
						this.imageList = [];
						this.location = '';
						this.selectedTopics = [];
						this.privacyIndex = 0;

						// 返回上一页
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/forum/forum'
							});
						}, 1500);
					}, 2000);
				} catch (error) {
					uni.showToast({
						title: '发布失败:' + error.message,
						icon: 'fail'
					});
					console.log('发布失败:', error.message);
				}
			},
			goShop() {
				uni.switchTab({
					url: '/pages/shop/shop'
				})
			},
			goIndex() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			goForum() {
				uni.switchTab({
					url: '/pages/forum/forum'
				})
			},
			goMine() {
				uni.switchTab({
					url: '/pages/mine/mine'
				})
			},
			goHealth() {
				uni.switchTab({
					url: '/pages/health/health'
				})
			},
			goShopCar() {
				uni.switchTab({
					url: '/pages/shop/shopCar'
				})
			},
		}
	}
</script>

<style scoped>
	.post-creation-container {
		background-color: #f4f4f4;
		min-height: 100vh;
		padding-bottom: 120rpx;
	}

	/* 顶部导航栏样式 */
	.top-navbar {
		background-color: white;
		padding: 15px 0;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 1000;
	}

	.logo {
		display: flex;
		align-items: center;
	}

	.logo image {
		width: 60px;
		height: 60px;
		margin-right: 15px;
	}

	.logo .titleText {
		font-size: 24px;
		font-weight: bold;
		color: #000000;
	}

	.navbar-center {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.nav-categories {
		display: flex;
	}

	.nav-item {
		padding: 8px 15px;
		color: #000000;
		font-size: 20px;
		font-weight: bold;
		cursor: pointer;
		margin-right: 10px;
		border-radius: 5px;
		transition: all 0.3s;
	}

	.nav-item:hover {
		background-color: rgba(255, 255, 255, 0.2);
	}

	.search-container {
		display: flex;
		align-items: center;
		background-color: rgba(255, 255, 255, 0.8);
		border-radius: 50px;
		box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
		max-width: 300px;
	}

	.search-container image {
		width: 20px;
		height: 20px;
		margin-left: 10px;
	}

	.search-input {
		flex: 1;
		border: none;
		outline: none;
		font-size: 15px;
		padding: 5px 5px;
		background-color: transparent;
	}

	.search-btn {
		background-color: #F9CB43;
		color: #fff;
		border: none;
		border-radius: 0 50px 50px 0;
		padding: 5px 15px;
		font-size: 14px;
		cursor: pointer;
	}

	.user-actions {
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}

	.action-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-left: 20px;
		cursor: pointer;
	}

	.action-item image {
		width: 24px;
		height: 24px;
	}

	.action-item .titleText {
		margin-top: 5px;
		color: #000000;
		font-size: 14px;
	}

	.post-form {
		background-color: #fff;
		padding: 30rpx;
		margin-bottom: 20rpx;
		margin-top: 270rpx;
	}

	.user-info {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.user-avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 40rpx;
		margin-right: 20rpx;
	}

	.username {
		font-size: 30rpx;
		font-weight: bold;
	}

	.content-area {
		position: relative;
		margin-bottom: 30rpx;
	}

	.content-input {
		width: 100%;
		min-height: 240rpx;
		font-size: 28rpx;
		line-height: 1.5;
		padding: 20rpx;
		box-sizing: border-box;
		border: 1px solid #eaeaea;
		border-radius: 10rpx;
	}

	.word-count {
		position: absolute;
		right: 20rpx;
		bottom: 20rpx;
		font-size: 24rpx;
		color: #999;
	}

	.section-subtitle {
		font-size: 28rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
		color: #333;
		display: block;
	}

	.upload-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.upload-count {
		font-size: 24rpx;
		color: #999;
	}

	.image-grid {
		display: flex;
		flex-wrap: wrap;
		margin: 0 -10rpx;
	}

	.image-item {
		position: relative;
		width: calc(33.33% - 20rpx);
		margin: 10rpx;
		height: 220rpx;
		border-radius: 10rpx;
		overflow: hidden;
	}

	.preview-image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.delete-btn {
		position: absolute;
		top: 10rpx;
		right: 10rpx;
		width: 40rpx;
		height: 40rpx;
		line-height: 36rpx;
		text-align: center;
		background-color: rgba(0, 0, 0, 0.6);
		color: #fff;
		border-radius: 20rpx;
		font-size: 36rpx;
	}

	.add-image {
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #f7f7f7;
		border: 1px dashed #ddd;
	}

	.add-icon {
		font-size: 60rpx;
		color: #999;
	}

	.topic-selection {
		margin: 30rpx 0;
	}

	.topic-scroll {
		white-space: nowrap;
	}

	.topic-item {
		display: inline-block;
		padding: 10rpx 30rpx;
		border-radius: 30rpx;
		background-color: #f7f7f7;
		margin-right: 20rpx;
		margin-bottom: .20rpx;
	}

	.topic-selected {
		background-color: #FFF5DC;
		color: #F9CB43;
		border: 1px solid #F9CB43;
	}

	.topic-text {
		font-size: 26rpx;
	}

	.location-area {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
		border-top: 1px solid #eaeaea;
		border-bottom: 1px solid #eaeaea;
		margin-bottom: 30rpx;
	}

	.location-icon {
		margin-right: 10rpx;
		font-size: 32rpx;
	}

	.location-text {
		flex: 1;
		font-size: 28rpx;
		color: #666;
	}

	.arrow-right {
		font-size: 24rpx;
		color: #999;
	}

	.clear-location {
		width: 40rpx;
		height: 40rpx;
		line-height: 36rpx;
		text-align: center;
		font-size: 30rpx;
		color: #999;
	}

	.privacy-setting {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
	}

	.privacy-label {
		font-size: 28rpx;
		color: #333;
	}

	.picker-value {
		display: flex;
		align-items: center;
		font-size: 28rpx;
		color: #666;
	}

	.submit-area {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		background-color: #fff;
		padding: 20rpx 30rpx;
		box-sizing: border-box;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.submit-btn {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		background-color: #F9CB43;
		color: #fff;
		font-size: 30rpx;
		font-weight: bold;
		border-radius: 40rpx;
	}

	.btn-disabled {
		background-color: #e6e6e6;
		color: #999;
	}
</style>